package io.renren.modules.dataInitialization.service.impl;

import io.renren.RandomString;
import io.renren.modules.dataInitialization.service.PersonnelDataService;
import io.renren.modules.jxgk.entity.CollegeInfoEntity;
import io.renren.modules.jxgk.service.WebSocket;
import io.renren.modules.jxgkphone.service.StuInfoService;
import io.renren.modules.jxgkphone.entity.StudentInfo;
import io.renren.modules.jxgk.entity.TeacherInfoEntity;
import io.renren.modules.pullin.service.PullOutService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class PersonnelDataServiceImpl implements PersonnelDataService {
    @Autowired
    PullOutService pullOutService;
    @Autowired
    StuInfoService stuInfoService;
    @Autowired
    WebSocket webSocket;
    private int dataCounter1=1;
    private int dataCounter2=1;
    private int dataCounter3=1;
    public void dataImportTeacher(InputStream inputStream){
        insertIntoDatabaseTeacher(excelToEntityTeacher(inputStream));
    }
    public void dataImportStudent(InputStream inputStream){
        insertIntoDatabaseStudent(excelToEntityStudent(inputStream));
    }
    public void dataImportCollegeInfo(InputStream inputStream){
        insertIntoDatabaseCollegeInfo(excelToEntityCollegeInfo(inputStream));
    }
    private void insertIntoDatabaseCollegeInfo(List<CollegeInfoEntity> collegeInfoEntities){
        for(CollegeInfoEntity t:collegeInfoEntities){
            if(t.getCollegeCode()!=null&&t.getCollegeCode()!=""){
                CollegeInfoEntity exist=pullOutService.findCollegeInfobyCollegeCode(t.getCollegeCode());
                CollegeInfoEntity existCopy=pullOutService.findCollegeInfoCopybyCollegeCode(t.getCollegeCode());
                if(exist!=null){
                    System.out.println("log:数据已存在,删除");
                    pullOutService.deleteCollegeInfoByCollegeCode(t.getCollegeCode());
                }
                if(existCopy!=null){
                    pullOutService.deleteCollegeInfoCopyByCollegeCode(t.getCollegeCode());
                }
                //学院信息表
                pullOutService.insertCollege(t);
                //副表
                pullOutService.insertCollegeCopy(t);
                System.out.println("log:更新学院信息表，本条第"+dataCounter3+"条");
                dataCounter3++;
                double percentage=dataCounter3*100/(collegeInfoEntities.size());
                //保留两位小数
                BigDecimal b = new BigDecimal(percentage);
                double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                webSocket.sendMessage(""+df);

            }
        }
        dataCounter3=0;
    }
    private void insertIntoDatabaseTeacher(List<TeacherInfoEntity> teacherInfos){
        for(TeacherInfoEntity t:teacherInfos){
            if(t.getTeacherId()!=null){
                TeacherInfoEntity exist=pullOutService.findTeacherInfobyTeacherId(t.getTeacherId());
                if(exist!=null){
                    System.out.println("log:数据已存在,删除");
                    pullOutService.deleteTeacherInfoByTeacherId(t.getTeacherId());
                    String usrId=stuInfoService.findUserIdByUserName(t.getTeacherId());
                    stuInfoService.DeleteUserRoleByUserId(usrId);
                    stuInfoService.DeleteUserByUserName(t.getTeacherId());
                }
                //教师信息表
                pullOutService.insertTeacher(t);
                //用户表
                String salt= RandomString.getRandomString(20);
                String password=new Sha256Hash("123456", salt).toHex();
                stuInfoService.AddStudentLeader(t.getTeacherId(),password,salt,1,1,t.getTeacherName());
                System.out.println("log:更新用户表");
                //用户角色表
                String usrId=stuInfoService.findUserIdByUserName(t.getTeacherId());
                stuInfoService.InsertUserRole(usrId,"3");
                System.out.println("log:更新用户角色表");
                System.out.println("log:更新教师信息表\n所有数据更新完成，本条第"+dataCounter1+"条");
                dataCounter1++;
                double percentage=dataCounter1*100/(teacherInfos.size());
                //保留两位小数
                BigDecimal b = new BigDecimal(percentage);
                double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                webSocket.sendMessage(""+df);

            }
        }
        dataCounter1=0;
    }
    public void insertIntoDatabaseStudent(List<StudentInfo> studentInfos){
        for(StudentInfo t:studentInfos){
            if(t.getStudentSchoolId()!=null){
                StudentInfo exist=pullOutService.findStudentInfoByStudentId(t.getStudentSchoolId());
                if(exist!=null){
                    System.out.println("log:数据已存在,删除");
                    pullOutService.deleteStudentInfoByStudentId(t.getStudentSchoolId());
                    String usrId=stuInfoService.findUserIdByUserName(t.getStudentSchoolId());
                    stuInfoService.DeleteUserRoleByUserId(usrId);
                    stuInfoService.DeleteUserByUserName(t.getStudentSchoolId());
                }
                //学生信息表
                t.setStudentClassId(t.getStudentClassName());
                pullOutService.insertStudentInfo(t);
                //用户表
                String salt= RandomString.getRandomString(20);
                String password=new Sha256Hash("123456", salt).toHex();
                stuInfoService.AddStudentLeader(t.getStudentSchoolId(),password,salt,1,1,t.getStudentName());
                System.out.println("log:更新用户表");
                //用户角色表
                String usrId=stuInfoService.findUserIdByUserName(t.getStudentSchoolId());
                stuInfoService.InsertUserRole(usrId,"1");
                System.out.println("log:更新用户角色表");
                System.out.println("log:更新学生信息表\n所有数据更新完成，本条第"+dataCounter2+"条");
                dataCounter2++;
                double percentage=dataCounter2*100/(studentInfos.size());
                //保留两位小数
                BigDecimal b = new BigDecimal(percentage);
                double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                webSocket.sendMessage(""+df);


            }

        }
        //导入完毕后 生成班级数据 先删除再生成
        pullOutService.DeleteClassInfo();
        pullOutService.InsertClassInfo();
        //清零
        dataCounter2=0;
    }
    //学院数据转实体链表
    private List<CollegeInfoEntity> excelToEntityCollegeInfo(InputStream inputStream) {
        List<CollegeInfoEntity> collegeInfoEntities=new ArrayList<>();
        HSSFWorkbook wb = null;
        //保存文件信息
        try {
            wb = new HSSFWorkbook(inputStream);
            HSSFSheet sheet = wb.getSheetAt(0);
            //直接把表头直接加上了，如果数据没错乱的话，可以直接导入。
            int firstRound=1;
            int position[]=new int[2];
            for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++){
                HSSFRow row = sheet.getRow(i);
                Iterator cells = row.cellIterator();
                CollegeInfoEntity temp=new CollegeInfoEntity();
                collegeInfoEntities.add(temp);
                int j=1;
                //初始化数据在Excel中的位置
                while (cells.hasNext()&&firstRound==1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(s.equals("学院名称"))
                        position[0]=j;
                    if(s.equals("学院代码"))
                        position[1]=j;
                    j++;
                }
                firstRound=2;
                while(cells.hasNext()&&firstRound!=1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(j==position[0])
                        temp.setCollegeName(s);
                    if(j==position[1])
                        temp.setCollegeCode(s);
                    j++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return collegeInfoEntities;
    }

    //教师excel数据转实体链表
    private List<TeacherInfoEntity> excelToEntityTeacher(InputStream inputStream) {
        List<TeacherInfoEntity> teacherInfos=new ArrayList<>();
        HSSFWorkbook wb = null;
        //保存文件信息
        try {
            wb = new HSSFWorkbook(inputStream);
            HSSFSheet sheet = wb.getSheetAt(0);
            //直接把表头直接加上了，如果数据没错乱的话，可以直接导入。
            int firstRound=1;
            int position[]=new int[6];
            for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++){
                HSSFRow row = sheet.getRow(i);
                Iterator cells = row.cellIterator();
                TeacherInfoEntity temp=new TeacherInfoEntity();
                teacherInfos.add(temp);
                int j=1;
                //初始化数据在Excel中的位置
                while (cells.hasNext()&&firstRound==1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(s.equals("职工号"))
                        position[0]=j;
                    if(s.equals("姓名"))
                        position[1]=j;
                    if(s.equals("性别"))
                        position[2]=j;
                    if(s.equals("出生日期"))
                        position[3]=j;
                    if(s.equals("所属部门"))
                        position[4]=j;
                    if(s.equals("教师类型"))
                        position[5]=j;
                    j++;
                }
                firstRound=2;
                while(cells.hasNext()&&firstRound!=1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(j==position[0])
                        temp.setTeacherId(s);
                    if(j==position[1])
                        temp.setTeacherName(s);
                    if(j==position[2])
                        temp.setTeacherSexual(s);
                    if(j==position[3])
                        temp.setTeacherBirthday(s);
                    if(j==position[4])
                        temp.setTeacherCollege(s);
                    if(j==position[5])
                        temp.setTeacherType(s);
                    j++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return teacherInfos;
    }


    //学生excel数据转实体链表
    private List<StudentInfo> excelToEntityStudent(InputStream inputStream) {
        List<StudentInfo> studentInfos=new ArrayList<>();
        HSSFWorkbook wb = null;
        //保存文件信息
        try {
            wb = new HSSFWorkbook(inputStream);
            HSSFSheet sheet = wb.getSheetAt(0);
            int firstRound=1;
            int position[]=new int[10];
            for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++){
                HSSFRow row = sheet.getRow(i);
                Iterator cells = row.cellIterator();
                StudentInfo temp=new StudentInfo();
                studentInfos.add(temp);
                int j=1;
                //初始化数据在Excel中的位置
                while (cells.hasNext()&&firstRound==1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(s.equals("学号"))
                        position[0]=j;
                    if(s.equals("班级名称"))
                        position[1]=j;
                    if(s.equals("姓名"))
                        position[2]=j;
                    if(s.equals("性别"))
                        position[3]=j;
                    if(s.equals("出生日期"))
                        position[4]=j;
                    if(s.equals("学院名称"))
                        position[5]=j;
                    if(s.equals("专业名称"))
                        position[6]=j;
                    if(s.equals("专业代码"))
                        position[7]=j;
                    if(s.equals("学制"))
                        position[8]=j;
                    if(s.equals("当前所在学年"))
                        position[9]=j;
                    j++;
                }
                firstRound=2;
                while(cells.hasNext()&&firstRound!=1){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(j==position[0])
                        temp.setStudentSchoolId(s);
                    if(j==position[1])
                        temp.setStudentClassName(s);
                    if(j==position[2])
                        temp.setStudentName(s);
                    if(j==position[3])
                        temp.setStudentSexual(s);
                    if(j==position[4])
                        temp.setStudentBirthday(s);
                    if(j==position[5])
                        temp.setStudentDepartment(s);
                    if(j==position[6])
                        temp.setStudentProfessionName(s);
                    if(j==position[7])
                        temp.setStudentProfessionCode(s);
                    if(j==position[8])
                        temp.setStudentSchoolingYear(s);
                    if(j==position[9])
                        temp.setStudentCurrentGrade(s);
                    j++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return studentInfos;
    }

}
